<template>
    <TheElDialog :title="title" :visible.sync="centerDialogVisible" @close="handleCenterDialogClose" v-bind="$attrs">
        <el-form
            @submit.native.prevent
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '80px' : '120px'"
        >
            <el-form-item prop="name" label="角色名称">
                <el-input :disabled="isDetail" v-model="form.name" placeholder="请填写角色名称"></el-input>
            </el-form-item>
            <el-form-item prop="permission" label="权限">
                <PermissionCheckboxGroup
                    :is-detail="isDetail"
                    :model-permission="modelPermission"
                    @change="handlePerimissionChange"
                    v-model="form.permission"
                    form-label-width="0px"
                />
            </el-form-item>
            <el-form-item prop="remark" label="备注">
                <el-input
                    :disabled="isDetail"
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请填写角色备注"
                ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
            <el-button
                :disabled="isDetail"
                :loading="centerDialogLoading"
                type="primary"
                @click="handleSubmit('formRule')"
                >确 定</el-button
            >
        </span>
    </TheElDialog>
</template>
<script>
import {postRoles, putRoles} from '@/api/role';
import {deepCopy} from '@/utils/utils';
import PermissionCheckboxGroup from '@/components/PermissionCheckboxGroup/index.vue';
export default {
    name: 'center-dialog',
    props: {
        title: {
            type: String,
            default: ''
        },
        visible: {
            type: Boolean,
            default: false
        },
        dataSource: {
            type: Object,
            default: () => ({
                id: undefined,
                name: '',
                remark: '',
                modelPermission: {
                    childModules: [],
                    functionMap: {},
                    parentModules: [],
                    selectedFunctions: [],
                    selectedModules: []
                }
            })
        }
    },
    components: {
        PermissionCheckboxGroup
    },
    data() {
        const validatePermission = (rule, value, callback) => {
            const newVal = value || [];
            const length = newVal.length;
            if (length === 0) {
                return callback(new Error('权限为空'));
            }
            callback();
        };
        const validatorPermissionsIds = (rule, value, callback) => {
            if (!Array.isArray(value) || (Array.isArray(value) && value.length === 0)) {
                return callback(new Error('权限不能为空'));
            }
            callback();
        };

        return {
            modelPermission: {
                childModules: [],
                functionMap: {},
                parentModules: [],
                selectedFunctions: [],
                selectedModules: []
            }, // 权限数据

            // 新建弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '320px'},
            // 新建表单
            form: {
                id: undefined,
                name: '',
                remark: '',
                permission: []
            },
            rules: {
                name: [{required: true, message: '请填写用户名', trigger: ['change', 'blur']}],
                permission: [
                    {required: true, message: '权限不能为空', trigger: 'change'},
                    {validator: validatorPermissionsIds, trigger: 'change'}
                ]
                // remark: [{required: false, message: '请填角色备注', trigger: ['change', 'blur']}]
            }
        };
    },
    computed: {
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        isDetail() {
            return this.title === '查看角色';
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                const modelPermission = val.modelPermission || {};
                this.form = {
                    id: val.id,
                    name: val.name,
                    remark: val.remark,
                    permission: []
                };

                this.modelPermission = deepCopy(modelPermission);
            },
            deep: false,
            immediate: false
        }
    },
    methods: {
        handlePerimissionChange() {
            // 自定义校验permissions_ids
            this.$refs['formRule'].validateField('permission');
        },
        // 提交表单
        handleSubmit(formName) {
            this.$refs[formName].validate((valid, fields) => {
                if (valid) {
                    const {id, name, remark, permission} = this.form;
                    const newRole = {
                        id,
                        name,
                        remark,
                        permission: permission.join(',')
                    };

                    if (this.title === '添加角色') {
                        this.handleCreateRole(newRole);
                    }
                    if (this.title === '编辑角色') {
                        this.handlePutRole(newRole);
                    }
                } else {
                    const first = Object.keys(fields)[0];
                    const items = fields[first] || [];
                    const {message} = items[0] || {};
                    this.$message({showClose: true, type: 'error', message});
                    return false;
                }
            });
        },
        // 创建角色
        handleCreateRole(newRole) {
            this.centerDialogLoading = true;
            postRoles(newRole)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建角色成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        handlePutRole(newRole) {
            this.centerDialogLoading = true;
            putRoles(newRole.id, newRole)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新角色成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');
            this.form = {
                id: undefined,
                name: '',
                remark: '',
                permission: []
            };
        }
    }
};
</script>
